package com.zb.security.tag;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.springframework.util.StringUtils;

import com.zb.common.po.model.Menu;
import com.zb.common.po.model.SessionUser;
import com.zb.common.utils.Constants;

public class PrivilegeTag extends TagSupport {
    private static final long serialVersionUID = -3779191462085763087L;
    // 权限
    private String permission;

    // 页面级权限认证
    public int doStartTag() throws JspException {
        HttpServletRequest request = (HttpServletRequest) pageContext
                .getRequest();
        boolean flag = this.validate(request);
        return flag ? EVAL_BODY_INCLUDE : SKIP_BODY;
    }

    private boolean validate(HttpServletRequest request) {
        if (permission == null) {
            return true;
        }
        SessionUser sessionUser = (SessionUser) request.getSession()
                .getAttribute(Constants.SESSION_KEY);
        List<Menu> menus = sessionUser.getMenuList();
        for (Menu menu : menus) {
            String permissinCode = menu.getPermissionCode();
            if (StringUtils.isEmpty(permissinCode)) {
                continue;
            }
            if (permissinCode.equals(permission)) {
                request.setAttribute("permUrl", menu.getMenuUrl());
                return true;
            }
        }
        return false;
    }

    public String getPermission() {
        return permission;
    }

    public void setPermission(String permission) {
        this.permission = permission;
    }
}
